<?php

namespace Modules\Common\Http\Controllers;

use AllowDynamicProperties;
use Illuminate\Http\Request;
use Modules\Common\Support\Upload\Uploader;
use Modules\System\Support\Upload;
use OSS\Core\OssException;
use OSS\Credentials\StaticCredentialsProvider;
use OSS\OssClient;


/**
 * @group 公共模块
 *
 * @subgroup 上传功能
 * @subgroupDescription CatchAdmin 上传
 */
#[AllowDynamicProperties] class UploadController
{

    public function __construct()
    {
        $this->accessKeySecret = env("ACCESSKEY");

        $this->accessKeyId = env("ACCESSSECRET");;

        $this->endpoint = env("ENDPOINT");


        $this->bucket = env("BUCKET");
    }
    /**
     * 文件上传
     *
     * @bodyParam category_id int required 分类ID
     * @bodyParam `file` file required 文件
     *
     * @responseField driver string 上传驱动名称
     * @responseField path string 上传路径(相对路径，如：/uploads/attachments/2024-09-17/2024V7zVurk7AU1726539554.png)
     * @responseField originName string 原文件名
     * @responseField size int 文件大小
     * @responseField type string 文件类型
     * @responseField ext string 文件扩展名
     * @responseField category_id int 分类ID
     *
     * @param Request $request
     * @param Uploader $uploader
     * @return array
     */
    public function file(Request $request, Uploader $uploader): array
    {
        return $uploader->withCategoryId($request->get('category_id', 0))
            ->upload($request->file('file'));
    }

    /**
     * 图片上传
     *
     * @bodyParam category_id int required 分类ID
     * @bodyParam `image` file required 图片
     *
     * @responseField driver string 上传驱动名称
     * @responseField path string 上传路径(相对路径，如：/uploads/attachments/2024-09-17/2024V7zVurk7AU1726539554.png)
     * @responseField originName string 原文件名
     * @responseField size int 文件大小
     * @responseField type string 文件类型
     * @responseField ext string 文件扩展名
     * @responseField category_id int 分类ID
     *
     * @param Request $request
     * @param Uploader $uploader
     * @return array
     */
    public function image(Request $request, Uploader $uploader): array
    {
        $file = $request->file('image');
        $saveDir = 'image/' . date('Ymd')."/".uniqid().".".$file->getClientOriginalExtension();
        $data['path'] = $this->upload($request->file('image'),$saveDir);
        return ($data);
    }

    /**
     * 第三方上传 token
     *
     * @queryParam driver string required 上传驱动名称
     *
     * @param Request $request
     * @return array
     */
    public function token(Request $request): array
    {
        $upload = new Upload();
        $method = $request->get('driver').'Token';

        return $upload->{$method}($request->get('filename'));
    }

    public function upload($file,$object)
    {
        // 从环境变量中获取访问凭证。运行本代码示例之前，请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。

        $accessKeyId = $this->accessKeyId;
        $accessKeySecret = $this->accessKeySecret;
// 使用代码嵌入的RAM用户的访问密钥配置访问凭证。
        $provider = new StaticCredentialsProvider($accessKeyId, $accessKeySecret);
// yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1（杭州）为例，Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
        $endpoint = $this->endpoint;
// 填写Bucket名称，例如example bucket。
        $bucket= $this->bucket;
// 填写Object完整路径，例如exampledir/exampleobject.txt。Object完整路径中不能包含Bucket名称。

// 填写本地文件的完整路径，例如D:\\localpath\\examplefile.txt。如果未指定本地路径，则默认从示例程序所属项目对应本地路径中上传文件。
        $filePath = $file->getRealPath();

        try{
            $config = array(
                "provider" => $provider,
                "endpoint" => $endpoint,
            );
            $ossClient = new OssClient($config);
            $result =  $ossClient->uploadFile($bucket, $object, $filePath);
            return $result['info']['url'];

        } catch(OssException $e) {
            printf(__FUNCTION__ . ": FAILED\n");
            printf($e->getMessage() . "\n");
            return $e;
        }
    }
}
